//
//  UpdataAddressViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/24.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyJSON

protocol UpdataAddressViewControllerDelegate {
    func giveTheAddressToAddressVC()
}

class UpdataAddressViewController: UIViewController,UITextFieldDelegate,UIScrollViewDelegate,CountryViewControllerDelegate {

    var delegate : UpdataAddressViewControllerDelegate?
    
    var myScrollView = UIScrollView()
    
    var firstNameTF = UITextField()
    var lastNameTF = UITextField()
    var countryTF = UITextField()
    var stateTF = UITextField()
    var cityTF = UITextField()
    var postCodeTF = UITextField()
    var telephoneTF = UITextField()
    var addressTF = UITextField()
    
    var countryStr = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.creatNavView()
        self.creatScrollView()
        self.creatAddView()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}
extension UpdataAddressViewController{
    fileprivate func creatNavView(){
        self.view.backgroundColor = UIColor.white
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.title = "UPDATE ADDRESS"
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "nav_back"), for: UIControlState())
        leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        
        
        let rightItemCustomeView   = UIButton(type: UIButtonType.custom)
        rightItemCustomeView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        rightItemCustomeView.setImage(UIImage(named:"nav_close"), for: UIControlState())
        rightItemCustomeView.addTarget(self, action: #selector(rightBtnClick), for: UIControlEvents.touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItemCustomeView);
        
        
    }
    
    func leftBtnClick(){
        self.navigationController?.popViewController(animated: true)
    }
    
    func rightBtnClick(){
        self.navigationController?.popToRootViewController(animated: true)
    }
    
}

extension UpdataAddressViewController{
    fileprivate func creatScrollView(){
        
        myScrollView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.9-64)
        myScrollView.delegate = self
        self.view.addSubview(myScrollView)
        
        self.customTextFieldWithTF(firstNameTF, labelString: "FIRSTNAME: ")
        firstNameTF.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.01, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        myScrollView.addSubview(firstNameTF)
        
        self.customTextFieldWithTF(lastNameTF, labelString: "LASTNAME: ")
        lastNameTF.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.09, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        myScrollView.addSubview(lastNameTF)
        
        self.customTextFieldWithTF(countryTF, labelString: "COUNTRY: ")
        countryTF.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.17, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        myScrollView.addSubview(countryTF)
        let countButton = UIButton(type: .custom)
        countButton.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.17, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        countButton.addTarget(self, action: #selector(countButtonClick), for: .touchUpInside)
        myScrollView.addSubview(countButton)
        
        self.customTextFieldWithTF(stateTF, labelString: "STATE: ")
        stateTF.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.25, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        myScrollView.addSubview(stateTF)
        
        self.customTextFieldWithTF(cityTF, labelString: "CITY: ")
        cityTF.frame =  CGRect(x: 20, y: SCREEN_HEIGHT*0.33, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        myScrollView.addSubview(cityTF)
        
        self.customTextFieldWithTF(postCodeTF, labelString: "POSTCODE: ")
        postCodeTF.frame =  CGRect(x: 20, y: SCREEN_HEIGHT*0.41, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        postCodeTF.delegate = self
        postCodeTF.tag = 1
        myScrollView.addSubview(postCodeTF)
        
        self.customTextFieldWithTF(telephoneTF, labelString: "TELEPHONE: ")
        telephoneTF.frame =  CGRect(x: 20, y: SCREEN_HEIGHT*0.49, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        telephoneTF.delegate = self
        telephoneTF.tag = 2
        myScrollView.addSubview(telephoneTF)
        
        self.customTextFieldWithTF(addressTF, labelString: "STREET ADDRESS: ")
        addressTF.frame =  CGRect(x: 20, y: SCREEN_HEIGHT*0.57, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT * 0.06)
        addressTF.delegate = self
        addressTF.tag = 3
        myScrollView.addSubview(addressTF)
    }
    
//    国家选择按钮点击事件
    func countButtonClick(){
        let countryVC = CountryViewController()
        countryVC.delegate = self
        self.navigationController?.pushViewController(countryVC, animated: true)
        
    }
    func giveTheCountryNameToUpDateVC(_ country: String, id: String) {
        countryTF.text = country
        countryStr = id
        
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        
        if textField.tag == 1 || textField.tag == 2 || textField.tag == 3 {
            UIView.animate(withDuration: 0.2, animations: { 
                self.myScrollView.frame = CGRect(x: 0, y: -SCREEN_HEIGHT*0.24, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.9-64)
            })
        }
        return true
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.tag == 1 || textField.tag == 2 || textField.tag == 3 {
            UIView.animate(withDuration: 0.2, animations: {
                self.myScrollView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.9-64)
            })
        }else{
            UIView.animate(withDuration: 0.2, animations: {
                self.myScrollView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.9-64)
            })

        }
        return true
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        UIView.animate(withDuration: 0.2, animations: {
            self.myScrollView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.9-64)
        })
        self.view.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        firstNameTF.resignFirstResponder()
        lastNameTF.resignFirstResponder()
        countryTF.resignFirstResponder()
        stateTF.resignFirstResponder()
        cityTF.resignFirstResponder()
        postCodeTF.resignFirstResponder()
        telephoneTF.resignFirstResponder()
        addressTF.resignFirstResponder()
    }
    
    func customTextFieldWithTF(_ textField:UITextField,labelString:String) {
        textField.clearButtonMode = .always
        textField.returnKeyType = .done
        textField.textAlignment = .left
        textField.contentVerticalAlignment = .center
        
        let label = UILabel()
        label.frame = CGRect(x: 5, y: 5, width: 20, height: 20)
        label.textColor = UIColor(red: 205/255.0, green: 205/255.0, blue: 205/255.0, alpha: 1)
        label.text = labelString
        label.sizeToFit()
        
        textField.leftView = label
        textField.leftViewMode = .always
        
    }
}

extension UpdataAddressViewController{
    fileprivate func creatAddView(){
        let addView = UIView()
        addView.frame = CGRect(x: 0, y: SCREEN_HEIGHT*0.9, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.1)
        addView.backgroundColor = UIColor.white
        self.view.addSubview(addView)
        
        let addBtn  = UIButton(type: .custom)
        addBtn.frame = CGRect(x: SCREEN_WIDTH*0.05, y: SCREEN_HEIGHT*0.01, width: SCREEN_WIDTH*0.9, height: SCREEN_HEIGHT*0.08)
        addBtn.setTitle("UPDATE", for: UIControlState())
        addBtn.setTitleColor(UIColor.white, for: UIControlState())
        addBtn.backgroundColor = UIColor.black
        addBtn.addTarget(self, action: #selector(addBtnClick), for: .touchUpInside)
        addView.addSubview(addBtn)
        
        
    }
    
    
    func addBtnClick(){
        
        let urlStr = APIBASE + "main_page=address_book_process"
        let parma = ["act":"add",
                     "firstname":firstNameTF.text!,
                     "lastname":lastNameTF.text!,
                     "zone_country_id":countryStr,
                     "state":stateTF.text!,
                     "city":cityTF.text!,
                     "postcode":postCodeTF.text!,
                     "customers_telephone":telephoneTF.text!,
                     "street_address":addressTF.text!,
                     "zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                
                SVProgressHUD.showSuccess(withStatus: "Shipping address fill out successfully!")
                self.delegate?.giveTheAddressToAddressVC()
                self.navigationController?.popViewController(animated: true)

            }else{
                SVProgressHUD.showError(withStatus: "get country data error:" + String(describing: error))
                print("get country data error:" + String(describing: error))
            }
        }
        
        
        
        
    }
    
    
    
}






